#include <stdio.h>
#include <pthread.h>
#include <wiringPi.h>

#include "control.h"
#include "global.h"
#include "smoke_interface.h"
#include "msg_queue.h"

#define SMOKE_PIN  6
#define SMOKE_MODE INPUT

static int smoke_init(void)
{
    pinMode(SMOKE_PIN,SMOKE_MODE);
    return -1;
}


static void *smoke_get(void *arg)
{
    unsigned char buffer[6] = {0xAA,0x55,0x00,0x00,0x55,0xAA};
    ctrl_info_t *ctrl_info = NULL;
    mqd_t mqd = -1;
    int smoke_signal = 0;
    int status = HIGH;
    int sendsize = -1;

    pthread_detach(pthread_self());
    printf("%s thread start\n", __func__);

    if(arg != NULL)
    {
        ctrl_info = (ctrl_info_t *)arg;
    }

    if(NULL != ctrl_info)
    {
        mqd =  ctrl_info->mqd;  
    }

    if ((mqd_t)-1 == mqd)
    {
        pthread_exit(0);
    }

    while(1)
    {
        status = digitalRead(SMOKE_PIN);
        if(status == LOW)
        {
            smoke_signal = 1;
            buffer[2] = 0x45;
            buffer[3] = 0x00;
            printf("%s|%s|%d:send 0x%x, 0x%x,0x%x, 0x%x, 0x%x,0x%x\n", __FILE__, __func__, __LINE__, buffer[0], buffer[1], buffer[2], buffer[3], buffer[4],buffer[5]);
            sendsize = mq_send(mqd,buffer,6,0);
            if(sendsize == -1)
            {
                continue;
            }
        }
        else if(status == HIGH && smoke_signal == 1)
        {
            smoke_signal = 0;
            buffer[2] = 0x45;
            buffer[3] = 0x01;
            printf("%s|%s|%d:send 0x%x, 0x%x,0x%x, 0x%x, 0x%x,0x%x\n", __FILE__, __func__, __LINE__, buffer[0], buffer[1], buffer[2], buffer[3], buffer[4],buffer[5]);
            sendsize = mq_send(mqd,buffer,6,0);
            if(sendsize == -1)
            {
                continue;
            }
        }
        sleep(5);
    }
    pthread_exit(0);
}







struct control smoke_control = {
    .control_name = "smoke",
    .init = smoke_init,
    .final = NULL,
    .get = smoke_get,
    .set = NULL,
    .next = NULL
};

struct control *add_smoke_to_ctrl_list(struct control *phead)
 {
    //头插法
    return add_interface_to_ctrl_list(phead, &smoke_control);
 };